library(ggplot2)
library(dplyr)
library(readr)

#setwd 

plot_data <- read_table("figures2_data.txt")

est_mod1 <- as.vector(plot_data[seq(1,13,2),2])
est_mod2 <- as.vector(plot_data[seq(1,13,2),3])
est_mod3 <- as.vector(plot_data[seq(1,13,2),4])
est_mod4 <- as.vector(plot_data[seq(1,13,2),5])

se_mod1 <- plot_data[seq(2,14,2),2]
se_mod2 <- plot_data[seq(2,14,2),3]
se_mod3 <- plot_data[seq(2,14,2),4]
se_mod4 <- plot_data[seq(2,14,2),5]

plot_data <- data_frame(est = c(est_mod1$X2, est_mod2$X3, est_mod3$X4, est_mod4$X5),
                        se  = c(se_mod1$X2,  se_mod2$X3,  se_mod3$X4, se_mod4$X5),
                        lab = rep(rep(c("DNES sample frame", "DNES respondents"), 2), each = 7), 
                        pla = c(rep(seq(1.2, 7.2, 1), 2),  rep(seq(0.8, 6.8, 1),  2)),
                        yea = rep(c("All voters", "Voters with validated turnout in 2015"), each = 14))


plot_data <- 
  plot_data %>% 
  mutate(est = 100 * as.numeric(est),
         se  = 100 * as.numeric(se))

plot_data[c(1,8,15,22),1:2] <- plot_data[c(1,8,15,22),1:2]*10

ggplot(data = na.omit(plot_data),
       aes(x = est,
           y = pla, 
           xmax = qnorm(0.975)*se + est,
           xmin = qnorm(0.025)*se + est)) + 
  geom_errorbarh(aes(color = yea), height = 0) + 
  geom_point(aes(color = yea), size = 3) + 
  theme_classic() + 
  facet_grid(. ~ lab) + 
  xlab("Difference in turnout") + 
  ylab("") +
  scale_y_continuous(breaks = 1:7,
                     labels = c("Age (10 years)",
                                "High School",
                                "Vocational training",
                                "Short/mid-cycle",
                                "Long-cycle",
                                "Female",
                                "Non-native")) +
  scale_color_manual(values=c("black", "grey75"),
                     guide_legend(title = "")) + 
  geom_vline(xintercept = 0, lty = 2, alpha = 0.3) +
  theme(legend.position = "top")

ggsave(plot = last_plot(), filename = "figureS2.pdf", width = 8, height = 4, dpi = 300)
